package com.luhuiguo.cms.client.presenter;

import com.extjs.gxt.ui.client.data.BaseListLoadResult;
import com.extjs.gxt.ui.client.data.ListLoadResult;
import com.extjs.gxt.ui.client.data.RpcProxy;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.inject.Inject;
import com.luhuiguo.cms.shared.event.LoadAttachmentsEvent;
import com.luhuiguo.cms.shared.event.LoadAttachmentsEventHandler;
import com.luhuiguo.cms.shared.model.AttachmentModel;
import com.luhuiguo.cms.shared.rpc.LoadAttachments;
import com.luhuiguo.cms.shared.rpc.LoadAttachmentsResult;
import com.luhuiguo.gwt.dispatcher.client.DispatcherAsync;
import com.luhuiguo.gwt.presenter.client.EventBus;

public class AttachmentProxy extends RpcProxy<ListLoadResult<AttachmentModel>> {

    @SuppressWarnings("unused")
    private EventBus eventBus;

    private DispatcherAsync dispatcher;

    private Long articleId;

    @Inject
    public AttachmentProxy(EventBus eventBus, DispatcherAsync dispatcher) {
        this.eventBus = eventBus;
        this.dispatcher = dispatcher;

        eventBus.addHandler(LoadAttachmentsEvent.TYPE, new LoadAttachmentsEventHandler() {
            @Override
            public void onLoadAttachments(LoadAttachmentsEvent event) {
                articleId = event.getArticleId();
            }
        });

    }

    @Override
    protected void load(final Object loadConfig, final AsyncCallback<ListLoadResult<AttachmentModel>> callback) {
        //ListLoadConfig cfg = (ListLoadConfig) loadConfig;

        dispatcher.execute(new LoadAttachments(articleId), new AsyncCallback<LoadAttachmentsResult>() {

            @Override
            public void onFailure(Throwable caught) {
                callback.onFailure(caught);

            }

            @Override
            public void onSuccess(LoadAttachmentsResult result) {
                callback.onSuccess(new BaseListLoadResult<AttachmentModel>(result.get()));

            }
        });

    }
}
